<template>
  <el-dialog :visible.sync="visible" v-bind="$attrs" :title="title" append-to-body>
    <div :class="$style.content">
      <!-- <el-carousel>
        <el-carousel-item v-for="(image,i) in imageList" :key="i">
          <img :src="prefix + image.url" :alt="image.name">
        </el-carousel-item>
      </el-carousel> -->
      <el-image
        v-for="(image,i) in list"
        :key="i"
        :ref="'image'+i"
        style="width: 100px; height: 100px"
        lazy
        :src="image"
        :preview-src-list="list"
        :class="$style.elimg"
        @click.stop="clickHandle(i)"
      >
      </el-image>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'PreviewImage',
  inheritAttrs: false,
  props: {
    imageList: {
      type: Array,
      default: () => []
    },
    value: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '图片预览'
    },
    prefix: {
      type: String,
      default: '/img/'
    }
  },
  data() {
    return {
      visible: false
    }
  },
  computed: {
    list() {
      return this.imageList.map(e => {
        if (e.status === 'ready') {
          return window.URL.createObjectURL(e.raw)
        } else {
          const objExp = new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/)
          if (!objExp.test(e.url)) {
            return `${this.prefix}${e.url}`
          } else {
            return e.url
          }
        }
      })
    }
  },
  watch: {
    visible(v) {
      this.$emit('input', v)
    },
    value(v) {
      this.visible = v
    }
  },
  created() {
    this.visible = this.value
  },
  methods: {
    clickHandle(i) {
      let img = this.$refs['image' + i]
      if (img) {
        if (img instanceof Array) {
          img = img[0]
        }
        this.$nextTick(() => {
          for (const c of img.$children || []) {
            c.index = i
          }
        })
      }
    }
  }
}
</script>
<style lang='scss' module>
.content{
  margin: -20px;
  padding: 10px;
  box-sizing: border-box;
  & > .elimg > img{
    width: 100%;
    height: 100%;
  }
  & i{
    text-align: center !important;
  }
}
.elimg:not(:first-child){
  margin-left: 10px;
}
</style>
<style>
.el-image-viewer__close{
  background: #fff;
}
</style>
